package com.yige.web.controller

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.ArgsUtil
import com.yige.common.ExcelFileGenerator
import com.yige.common.MD5Util
import com.yige.common.ResultUtil
import com.yige.common.SystemConstant
import com.yige.common.ToDBObjectUtil
import com.yige.service.mongoService.MongoRoleService
import com.yige.service.mongoService.MongoUserService
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.ModelMap
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.View
import org.springframework.web.servlet.view.document.AbstractExcelView

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * Created by sunhao on 2015/9/17 0017.
 */
@Controller
@RequestMapping("user")
class UserController {

    @Autowired
    MongoUserService userService
    @Autowired
    MongoRoleService roleService


    /*****************控制器模块*****************/

    /**
     * 跳转用户管理界面
     * @return
     */

    @RequestMapping("/list.do")
    def list(Model model){
        List<DBObject> userList = userService.findList()
        model.addAttribute("users",userList)
        return "user/list"
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @RequestMapping("addUser")
    @ResponseBody
    def addUser(String username, String email, Integer status) {
        //创建用户信息
        List<DBObject> role = new LinkedList<>()
        Map<String,Object> userInfo = [_id:UUID.randomUUID().toString(),
                                       username:username,
                                       password:SystemConstant.DEFAULT_PASSWORD,
                                       email:email,
                                       status:status,
                                       role:role,
                                       identity:"",
        ]
        DBObject dbObject = ToDBObjectUtil.toDBObject(userInfo)
        boolean  flag = saveUser(dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 多条件查询用户
     * @param model
     * @param username
     * @param email
     * @param status
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping("/find")
    def find(Model model, String username, String email, Integer status, String startDate, String endDate){
        def query = new BasicDBObject()
        def sdf = new SimpleDateFormat("yyyy-MM-dd")
        if(!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
            query.append("registerTime",[$gte:sdf.parse(startDate),$lte:sdf.parse(endDate)]as BasicDBObject)
        }else if(!StringUtils.isEmpty(startDate) && StringUtils.isEmpty(endDate)){
            query.append("registerTime",[$gte:sdf.parse(startDate)]as BasicDBObject)
        }else if(StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
            query.append("registerTime",[$lte:sdf.parse(endDate)]as BasicDBObject)
        }
        if(!StringUtils.isEmpty(username)){
            query.append("username",~/${username}/)
        }
        if(!StringUtils.isEmpty(email)){
            query.append("email",~/${email}/)
        }
        if(status == null){
            query.append("status",[$in:[1,0]]as BasicDBObject)
        } else if(status != -1){
            query.append("status",status)
        }
        List<DBObject> users = userService.findListByQuery(query)
        model.addAttribute("users",users)
        return "user/list"
    }

    /**
     * 修改用户
     * @param _id
     * @param username
     * @param password
     * @param email
     * @param status
     */
    @RequestMapping("updateUser")
    @ResponseBody
    def updateUser(String _id,String username, String email, Integer status){
        //创建用户信息
        List<DBObject> roleList = new ArrayList<>(userService.findAllRoleByUser(_id))
        String identity = userService.findOneById(_id).identity
        Map<String,Object> userInfo = [_id:_id,
                                       username:username,
                                       email:email,
                                       status:status,
                                       role: roleList,
                                       identity:identity]
        DBObject dbObject = ToDBObjectUtil.toDBObject(userInfo)
        boolean flag = updateUser(dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 删除用户
     * @param _ids
     * @return
     */
    @RequestMapping("delUser")
    @ResponseBody
    def delUser(@RequestParam("_ids") List<String> _ids){
        //遍历删除用户
        boolean flag = false
        _ids.each {_id->
            flag = userService.deleteOne(_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 根据Id查找用户
     * @param _id
     * @param model
     * @return
     */
    @RequestMapping("findUser")
    def findUser(String userId, Model model) {
        DBObject user = userService.findOneById(userId), role
        List<DBObject> roles = new ArrayList<>()
        user.role.each{roleId->
            role = roleService.findOneById(roleId)
            roles.add(role)
        }
        model.addAttribute("user",user)
        model.addAttribute("roles",roles)
        return "user/info"
    }


    /**
     * 显示用户角色
     * @param _id
     * @param model
     * @return
     */
    @RequestMapping("configureRole")
    def roleConfigure(String userId, Model model){
        DBObject user = userService.findOneById(userId),role
        List<DBObject> allRoles = roleService.findList(),
                       noRoles,
                       roles = new ArrayList<DBObject>()
        user.role.each {info->
            role = roleService.findOneById(info)
            if (allRoles.contains(role)){
                roles.add(role)
            }
        }
        if(roles != null || roles.size() != 0){
            allRoles.removeAll(roles)
        }
        noRoles = allRoles
        model.addAttribute("user",user)
        model.addAttribute("roles",roles)
        model.addAttribute("noRoles",noRoles)
        return "user/configure"
    }

    /**
     * 配置用户角色
     * @param _ids
     * @param user_id
     * @return
     */
    @RequestMapping("bindRole")
    @ResponseBody
    def bindRole(@RequestParam('_ids') List<String> _ids,
                 @RequestParam('userId') String userId){
        boolean flag = false
        _ids.each {_id->
            flag = userService.bindRoleForUser(userId,_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 解除用户角色
     * @param _ids
     * @param user_id
     * @return
     */
    @RequestMapping("removeRole")
    @ResponseBody
    def removeRole(@RequestParam('_ids') List<String> _ids,
                   @RequestParam('userId') String userId){
        boolean flag = false
        _ids.each {_id->
            flag = userService.removeRoleForUser(userId,_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    @RequestMapping("resetPwd")
    @ResponseBody
    def resetPwd(String userId){
        boolean flag = false
        def user_db = userService.findOneById(userId) as DBObject
        user_db.password = MD5Util.md5(SystemConstant.DEFAULT_PASSWORD)
        flag = userService.updateOne(userId,user_db)
        ResultUtil.recallAjax(flag)
    }


    /**
     * 导出用户表格
     * @param modelMap
     * @return
     */
    @RequestMapping("/export.do")
    def export(ModelMap modelMap){
        View view = new AbstractExcelView() {

            @Override
            protected void buildExcelDocument(Map map,
                                              HSSFWorkbook workbook, HttpServletRequest request,
                                              HttpServletResponse response) throws Exception {
                //定义Excel表参数
                String filename = new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls";
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + filename) ;

                // 建立 Sheet
                List<String> fieldName = new ArrayList<>()
                fieldName.add("ID")
                fieldName.add("用户名称")
                fieldName.add("邮箱")
                fieldName.add("创建日期")
                fieldName.add("状态")

                List<List<Object>> fieldData = new ArrayList<>()
                List<DBObject> userList = userService.findList()
                userList.each {info->
                    fieldData.add(
                            [info._id,
                             info.username,
                             info.email,
                             new SimpleDateFormat("yyyy-MM-dd").format(info.registerTime),
                             info.status]as ArrayList
                    )
                }
                ExcelFileGenerator excel = new ExcelFileGenerator(fieldName,fieldData)
                //开启输出流
                OutputStream outputStream = response.getOutputStream();
                //输出Excel表
                excel.exportExcel(outputStream)
            }
        }
        return new ModelAndView(view,modelMap)
    }


    /*****************方法模块*****************/


    def saveUser(DBObject userInfo){
        ArgsUtil.checkArgs(userInfo)
        // 判断用户名是否存在
        DBObject user_db = userService.findUserByName(userInfo.username)
        if (user_db == null) {
            // 用户名不存在，可以创建用户
            // 新增用户
            String md5Password = MD5Util.md5(userInfo.password)
            userInfo.put("password",md5Password)
            userInfo.put("registerTime",new Date(System.currentTimeMillis()))
            if (userInfo.status == null) {
                userInfo.put("status", SystemConstant.USER_ON_JOB)
            }
            userService.insertOne(userInfo)
            return true
        } else {
            // 用户名已存在
            return false
        }
    }

    def updateUser(DBObject userInfo) {
        ArgsUtil.checkArgs(userInfo)
        DBObject user_db = userService.findOneById(userInfo._id)
        userInfo.put("password",user_db.password)
        userInfo.put("registerTime",user_db.registerTime)
        userService.updateOne(userInfo._id,userInfo)
        return true
    }

}
